package dk.mirasola.systemtraining.user.client.ui;

import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.MultiSelectionModel;
import com.google.gwt.view.client.RowCountChangeEvent;
import com.google.gwt.view.client.SelectionChangeEvent;
import dk.mirasola.systemtraining.bridgewidgets.shared.model.distributionfiltertree.DistributionFilterGroup;
import dk.mirasola.systemtraining.user.client.dataprovider.UserDistributionFilterDataProvider;
import dk.mirasola.systemtraining.user.client.i18n.UserDistributionFilterTableTexts;
import dk.mirasola.systemtraining.user.client.ui.table.STCellTableResource;
import dk.mirasola.systemtraining.user.client.ui.table.SafeHtmlColumn;
import dk.mirasola.systemtraining.user.client.util.DistributionFilterGroupRender;
import dk.mirasola.systemtraining.user.shared.transfer.UserDistributionFilterTO;

import java.util.Set;

public class UserDistributionFilterTable extends Composite {
    interface UserDistributionFilterTableUiBinder extends UiBinder<Widget, UserDistributionFilterTable> {}
    private static UserDistributionFilterTableUiBinder uiBinder = GWT.create(UserDistributionFilterTableUiBinder.class);
    private static UserDistributionFilterTableTexts texts = GWT.create(UserDistributionFilterTableTexts.class);

    @UiField(provided = true)
    CellTable<UserDistributionFilterTO> table;
    @UiField
    SimplePager pager;
    @UiField
    Button createButton;
    @UiField
    Button deleteButton;
    @UiField
    Button editButton;
    @UiField
    Button copyButton;

    private UserDistributionFilterDataProvider dataProvider = new UserDistributionFilterDataProvider();
    private MultiSelectionModel<UserDistributionFilterTO> selectionModel = new MultiSelectionModel<UserDistributionFilterTO>();

    public UserDistributionFilterTable() {
        initTable();
        initWidget(uiBinder.createAndBindUi(this));
        dataProvider.addDataDisplay(table);
        pager.setDisplay(table);

        initCreateButton();
        initDeleteButton();
        initEditButton();
        intiCopyButton();


        selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
            @Override
            public void onSelectionChange(SelectionChangeEvent event) {
                int selCount = selectionModel.getSelectedSet().size();
                deleteButton.setEnabled(selCount > 0);
                editButton.setEnabled(selCount == 1);
                copyButton.setEnabled(selCount == 1);
            }
        });
    }

    private void intiCopyButton() {
        copyButton.setHTML(texts.copyButton());
        copyButton.setEnabled(false);
        copyButton.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                UserDistributionFilterTO sel = selectionModel.getSelectedSet().iterator().next();
                if (sel != null) {
                    UserDistributionFilterTO copy = new UserDistributionFilterTO();
                    copy.setName(sel.getName());
                    copy.setDescription(sel.getDescription());
                    copy.setDistributionFilter(sel.getDistributionFilter().copy());
                    edit(copy);
                }
            }
        });
    }

    private void initEditButton() {
        editButton.setHTML(texts.editButton());
        editButton.setEnabled(false);
        editButton.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                UserDistributionFilterTO sel = selectionModel.getSelectedSet().iterator().next();
                if (sel != null) {
                    edit(sel);
                }
            }
        });
    }

    private void initDeleteButton() {
        deleteButton.setHTML(texts.deleteButton());
        deleteButton.setEnabled(false);
        deleteButton.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                Set<UserDistributionFilterTO> selections = selectionModel.getSelectedSet();
                selectionModel.clear();
                if (selections != null && selections.size() > 0) {
                    dataProvider.deleteUserDistributionFilters(selections);
                }
            }
        });
    }

    private void initCreateButton() {
        createButton.setHTML(texts.newButton());
        createButton.setEnabled(false);
        pager.getDisplay().addRowCountChangeHandler(new RowCountChangeEvent.Handler() {
            @Override
            public void onRowCountChange(RowCountChangeEvent event) {
                createButton.setEnabled(event.getNewRowCount() < dataProvider.getMaxUserDistributionFilters());
            }
        });
        createButton.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                UserDistributionFilterTO c = new UserDistributionFilterTO();
                c.setName(texts.newUserDistributionFilterName());
                c.setDescription(texts.newUserDistributionFilterDescription());
                DistributionFilterGroup root = new DistributionFilterGroup(texts.newUserDistributionFilterRootGroupName());
                c.setDistributionFilter(root);
                edit(c);
            }
        });
    }

    private void initTable() {
        CellTable.Resources resources = GWT.create(STCellTableResource.class);
        table = new CellTable<UserDistributionFilterTO>(5, resources);
        table.setSelectionModel(selectionModel);

        Column<UserDistributionFilterTO, Boolean> selectColumn = new Column<UserDistributionFilterTO, Boolean>(new CheckboxCell(true, true)) {
            @Override
            public Boolean getValue(UserDistributionFilterTO object) {
                return selectionModel.isSelected(object);
            }
        };
        selectColumn.setFieldUpdater(new FieldUpdater<UserDistributionFilterTO, Boolean>() {
            @Override
            public void update(int index, UserDistributionFilterTO object, Boolean value) {
                selectionModel.setSelected(object, value);
            }
        });

        TextColumn<UserDistributionFilterTO> nameColumn = new TextColumn<UserDistributionFilterTO>() {
            @Override
            public String getValue(UserDistributionFilterTO userDistributionFilter) {
                return userDistributionFilter.getName();
            }
        };

        TextColumn<UserDistributionFilterTO> descColumn = new TextColumn<UserDistributionFilterTO>() {
            @Override
            public String getValue(UserDistributionFilterTO userDistributionFilter) {
                return userDistributionFilter.getDescription();
            }
        };

        SafeHtmlColumn<UserDistributionFilterTO> filterColumn = new SafeHtmlColumn<UserDistributionFilterTO>() {
            @Override
            public SafeHtml getValue(UserDistributionFilterTO userDistributionFilter) {
                return DistributionFilterGroupRender.renderDistributionFilterGroup(userDistributionFilter.getDistributionFilter());
            }
        };

        table.addColumn(selectColumn);
        table.addColumn(nameColumn, texts.nameColumn());
        table.addColumn(descColumn, texts.descriptionColumn());
        table.addColumn(filterColumn, texts.distributionFilterColumn());
    }

    private void edit(UserDistributionFilterTO userDistributionFilter) {
        final PopupPanel popupPanel = new PopupPanel(false, true);
        popupPanel.setAnimationEnabled(true);
        popupPanel.setSize("600px", "500px");
        UserDistributionFilterEditor editor = prepareEditor(userDistributionFilter, popupPanel);
        popupPanel.setWidget(editor);
        popupPanel.center();
        editor.getNameTextBox().setFocus(true);
    }

    private UserDistributionFilterEditor prepareEditor(UserDistributionFilterTO userDistributionFilter, final PopupPanel popupPanel) {
        final UserDistributionFilterEditor userDistributionFilterEditor = new UserDistributionFilterEditor(userDistributionFilter);
        userDistributionFilterEditor.getCancelButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                popupPanel.hide();
            }
        });
        userDistributionFilterEditor.getSaveAndCloseButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                popupPanel.hide();
                UserDistributionFilterTO userDistributionFilter = userDistributionFilterEditor.flush();
                if (userDistributionFilter.getId() != null) {
                    dataProvider.updateUserDistributionFilter(userDistributionFilter);
                } else {
                    dataProvider.createUserDistributionFilter(table,userDistributionFilter);
                }
            }
        });
        return userDistributionFilterEditor;
    }
}

